#-*- coding: utf-8 -*
import serial
import serial.tools.list_ports
import binascii
import time


class Myserial(object):
    '''
        This is a serial class defined by users.
        you can use it to do what you want by serial device
    '''

    def __init__(self, serial_baud=9600, serial_port=''):
        self.serial_baud = serial_baud
        if serial_port == '':
            self.serial_port_info = self.get_serial_port()
            if self.serial_port_info[0] == 'False':
                print("Check the connection of your device!!!")
            elif self.serial_port_info[0] == 'True':
                self.serial_port = self.serial_port_info[1]
        else:
            self.serial_port = serial_port
        # instantiate(实例化) the serial object
        self.current_serial_port = serial.Serial(self.serial_port, self.serial_baud)

    def get_serial_port(self):
        '''
        function:get the serial port
        return:
            port_find['False','0']:there is no serial port
            port_find['True',serial_port]:there is a serial port,and the serial port is a string data
        '''
        port_find = ['', '']
        port_list = list(serial.tools.list_ports.comports())

        if len(port_list) <= 0:
            port_find = ['False', '0']

            return port_find

        else:
            port_list_0 = list(port_list[0])
            port_serial = port_list_0[0]
            port_find = ['True', port_serial]

            return port_find

    def get_RxData_str(self):
        '''
            function: receive the data from the serial port,except for your defined port
            return:the length of this receive,and a list of this receive data 
        '''
        bufsize = 0
        RxData_buf = []
        RxData_len = 0

        while bufsize == 0:
            # wait for the end of the receiving and get the length of receive_buf
            bufsize = self.current_serial_port.inWaiting()
            continue
        # get the receive data,the data's type is as same as the serial port sended
        buf_str = (self.current_serial_port.read(bufsize))
        # exchange the data to str and encapsulate(封装) it as a list 
        for i in range(len(buf_str)):
            RxData_buf.append(binascii.b2a_hex(buf_str[i]))
        
        # clear the flush waitting for next receive
        self.current_serial_port.flushInput()
        # get the length of this receive
        RxData_len = bufsize
        bufsize = 0

        return RxData_len, RxData_buf

    def get_RxData_org(self):
        '''
            function: receive the data from the serial port,except for your defined port
            return:the length of this receive,and a list of this receive data 
        '''
        bufsize = 0
        RxData_buf = []
        RxData_len = 0

        while (bufsize == 0) or (bufsize == 1):
            # wait for the end of the receiving and get the length of receive_buf
            bufsize = self.current_serial_port.inWaiting()
            continue
        # get the receive data,the data's type is as same as the serial port sended
        RxData_buf = (self.current_serial_port.read(bufsize))
        # clear the flush waitting for next receive
        self.current_serial_port.flushInput()
        # get the length of this receive
        RxData_len = bufsize
        bufsize = 0

        return RxData_len, RxData_buf

    def send_TxData(self,TxData, TxData_type='str', sleepNum=0):
        '''
            function:send data by serial ,the data's type can be 'str' and 'hex'.
        '''
        if TxData_type == 'str':
            self.current_serial_port.write(TxData)
        else:
            self.current_serial_port.write(hex(TxData))
        time.sleep(sleepNum)

    def send_commd(self,TxData, TxData_type='str', sleepNum=0):
        '''
            function: send commd data and get the receive_buf's length
            return:the length of receive_buf
        '''
        self.current_serial_port.write(TxData)
        time.sleep(sleepNum)
        length = self.current_serial_port.inWaiting()
        return length

    def conver_pyhex2hex(self, pyhex_data):
        '''
            function：transform the type of pyhex_data to a real data_hex
            return:the real data_hex of pyhex_data
            本函数将python中的类型16进制方式的数据转换为真实16进制值(非python类型的16进制),并且返回
        '''
        hexdata = int(binascii.b2a_hex(pyhex_data), 16)
        return hexdata

    
